<?php
namespace App\Job;

use Hyperf\AsyncQueue\Annotation\AsyncQueueMessage;

use App\Facade\Http;
use App\Repository\UserIntegralRepository;

// 远程商品积分
class ApiIntegralJob
{
    /**
     * @AsyncQueueMessage
     */
    public function push($id)
    {
        if(!$model = UserIntegralRepository::find($id))
        {
            return;
        }
        
        // 状态
        if($model->statusOk())
        {
            return;
        }
        
        // 远程地址
        $http = Http::create([
            'base_uri' => 'http://127.0.0.1:8001/'
        ]);
        
        // 提交积分
        [$res, $body] = $this->add($http, $model->phone, (int) $model->integral);
        
        if(!$res)
        {
            // 标识失败
            return $model->setStatusNo($body); 
        }
        
        // 标识成功
        $model->setStatusOk($body); 
    }
    
    // 提交积分
    public function add($http, $phone, $integral)
    {
        $response = $http->get('/userIntegral/add', [
            'query' => compact('phone', 'integral')
        ]);
        
        $body = (string) $response->getBody();
        $res = json_decode($body);
        
        // 是否成功
        return [$res->status == 0, $body];
    }
}